package com.zego.wawaji.ui.center.question.adapter;

import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.noble.library.observer.MsgMgr;
import com.zego.wawaji.R;
import com.zego.wawaji.base.module.ModuleMgr;
import com.zego.wawaji.base.observer.MsgType;
import com.zego.wawaji.base.toast.PToast;
import com.zego.wawaji.http.request.HttpResponse;
import com.zego.wawaji.http.request.RequestComplete;
import com.zego.wawaji.http.request.UrlParam;
import com.zego.wawaji.ui.base.recycler.BaseRecyclerViewAdapter;
import com.zego.wawaji.ui.base.recycler.BaseRecyclerViewHolder;
import com.zego.wawaji.ui.center.question.bean.Question;
import com.zego.wawaji.wawaji_client.AppTinkerLike;

import java.util.List;

/**
 * 我的问题反馈列表
 * Created by Su on 2018/4/12.
 */
public class MyQuestionAdapter extends BaseRecyclerViewAdapter<Question> implements RequestComplete {
    @Override
    public int[] getItemLayouts() {
        return new int[]{R.layout.question_my_item};
    }

    @Override
    public void onBindRecycleViewHolder(BaseRecyclerViewHolder viewHolder, int position) {
        final Question data = getItem(position);

        TextView q_content = viewHolder.findViewById(R.id.q_content);
        TextView q_reply = viewHolder.findViewById(R.id.q_reply);
        TextView tv_status = viewHolder.findViewById(R.id.tv_status);
        LinearLayout ll_function = viewHolder.findViewById(R.id.ll_function);
        LinearLayout btn_qq = viewHolder.findViewById(R.id.btn_qq);
        TextView btn_finish = viewHolder.findViewById(R.id.btn_finish);

        initStatus(data.getFeedStatus(), tv_status, ll_function);
        q_content.setText(data.getContent());
        q_reply.setText(data.getReply());

        btn_qq.setOnClickListener(v -> {
            copyContent("用户ID：" + ModuleMgr.getCenterMgr().getMyInfo().getUid() + "\n问题描述：" + data.getContent()
                    + "\n回复内容：" + data.getReply());
            openQQ();
        });

        btn_finish.setOnClickListener(v -> ModuleMgr.getWawaMgr().reqQuestionStatus(data.getId(), MyQuestionAdapter.this));

    }

    private void initStatus(int status, TextView tvStatus, LinearLayout ll_function) {
        if (status == -3) { // 待解决
            tvStatus.setText("待解决");
            tvStatus.setBackgroundResource(R.drawable.bg_question_orange);
            ll_function.setVisibility(View.GONE);
            return;
        }

        if (status == -2) { // 已回复
            tvStatus.setText("已回复");
            tvStatus.setBackgroundResource(R.drawable.bg_question_orange);
            ll_function.setVisibility(View.VISIBLE);
            return;
        }

        if (status == -1) {
            tvStatus.setText("未解决");
            tvStatus.setBackgroundResource(R.drawable.bg_question_orange);
            ll_function.setVisibility(View.VISIBLE);
            return;
        }

        if (status == 1) {
            tvStatus.setText("已解决");
            tvStatus.setBackgroundResource(R.drawable.bg_question_gray);
            ll_function.setVisibility(View.GONE);
        }
    }

    @Override
    public void onRequestComplete(HttpResponse response) {
        if (response.getUrlParam() == UrlParam.reqQuestionStatus) {
            if (!response.isOk()) {
                PToast.showShort(response.getMsg());
                return;
            }
            MsgMgr.getInstance().sendMsg(MsgType.MT_Refresh_Question, null);
        }
    }

    /**
     * 复制到剪切板
     */
    private void copyContent(String content) {
        if (Build.VERSION.SDK_INT > 11) {
            // 得到剪贴板管理器
            android.content.ClipboardManager clipboard = (android.content.ClipboardManager) AppTinkerLike.getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
            clipboard.setPrimaryClip(ClipData.newPlainText("Label", content));
        } else {
            android.text.ClipboardManager cmb = (android.text.ClipboardManager) AppTinkerLike.getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
            cmb.setText(content);
        }
        PToast.showShort("问题已复制到剪切板");
    }

    @Override
    public int getRecycleViewItemType(int position) {
        return 0;
    }

    // =============================== 客服QQ会话 ===========================
    private void openQQ() {
        // 跳转之前，可以先判断手机是否安装QQ
        if (isQQClientAvailable(AppTinkerLike.getActivity())) {
            // 跳转到客服的QQ
            String url = "mqqwpa://im/chat?chat_type=wpa&uin=3338566907";
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            // 跳转前先判断Uri是否存在，如果打开一个不存在的Uri，App可能会崩溃
            if (isValidIntent(AppTinkerLike.getActivity(), intent)) {
                AppTinkerLike.getActivity().startActivity(intent);
            }
        }
    }

    /**
     * 判断 用户是否安装QQ客户端
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equalsIgnoreCase("com.tencent.qqlite") || pn.equalsIgnoreCase("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断 Uri是否有效
     */
    public static boolean isValidIntent(Context context, Intent intent) {
        PackageManager packageManager = context.getPackageManager();
        List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
        return !activities.isEmpty();
    }
}
